﻿using System;
using System.Net;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml;
using Def.Log;

namespace FrontDisplay.Weather
{
    /// <summary>
    /// Interaction logic for ParametersPage.xaml
    /// </summary>
    public partial class ParametersPage : UserControl
    {
        private City _selectedCity;

        public City SelectedCity
        {
            get { return _selectedCity; }
            set
            {
                _selectedCity = value;
                CityName.Text = _selectedCity.Name;
            }
        }

        public ParametersPage()
        {
            InitializeComponent();
        }

        private void LinkLabelMouseDown(object sender, MouseButtonEventArgs e)
        {
            System.Diagnostics.Process.Start("http://weather.yahoo.com/");
        }

        private void SearchButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            string searchText = SearchCityName.Text.Trim();
            if (string.IsNullOrEmpty(searchText)) return;

            SearchButton.IsEnabled = false;

            var client = new WebClient();
            client.DownloadStringCompleted += DownloadCityListCompleted;
            Uri searchUrl = new Uri(string.Format("http://xoap.weather.com/search/search?where={0}", searchText));
            client.DownloadStringAsync(searchUrl, null);
        }

        private void DownloadCityListCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            SearchButton.IsEnabled = true;
            CityList.Items.Clear();

            if (e.Error != null)
            {
                Logger.Error(e.Error);
                return;
            }

            try
            {
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(e.Result);
                if (xml.DocumentElement == null) return;

                foreach (XmlNode node in xml.DocumentElement.ChildNodes)
                {
                    if (node.Name == "loc")
                    {
                        CityList.Items.Add(new City(node));
                    }
                }
            }
            catch (XmlException ex)
            {
                Logger.Error(ex);
            }
        }

        private void CityListMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            City cityItem = (CityList.SelectedItem as City);
            if (cityItem == null) return;

            SelectedCity = cityItem;
            CityName.Text = SelectedCity.Name;
        }
    }
}
